package com.myjob.controller;

import com.myjob.config.PrivateKeyProperties;
import com.myjob.response.Result;
import com.myjob.service.ChangePasswordService;
import com.myjob.utils.RSAUtils;
import com.myjob.utils.UtilValidate;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

/**
 * @author chenyuan
 * @date 2020/12/31 10:42
 */
@RestController
@Slf4j
@RequestMapping("/account")
public class ChangePasswordController {
    @Autowired
    private ChangePasswordService changePasswordService;
    @Autowired
    private PrivateKeyProperties privateKey;

    /**
     * 按照 id 编号查询用户密码
     * @param userId 编号
     * @return
     */
    @GetMapping("/changePassword")
    public Result checkPasswordById(@RequestParam(value = "userId") String userId,
                                     @RequestParam(value = "password") String encodedPassword){
        Result result = null;
        try {
            if (UtilValidate.isEmpty(userId) ||
                    UtilValidate.isEmpty(encodedPassword)) {
                return Result.failed("参数为空");
            }
            encodedPassword = encodedPassword.replace(" ", "+");
            String password = RSAUtils.decryptRSADefault(privateKey.getPrivateKey(), encodedPassword);
            Boolean same = changePasswordService.checkPasswordById(userId, password);
            if (same){
                result = Result.succeed("密码正确");
            }else {
                result = Result.failed("密码验证失败");
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return result;
    }

    /**
     * 按照 id 编号， 修改密码
     * @param userId 编号
     * @param newPassword 新密码
     * @return
     */
    @PostMapping("/changePassword")
    public Result updatePasswordById(@RequestParam(value = "userId") String userId,
                                     @RequestParam(value = "newPassword") String encodedPassword){
        Result result = null;
        try {
            encodedPassword = encodedPassword.replace(" ", "+");
            String password = RSAUtils.decryptRSADefault(privateKey.getPrivateKey(), encodedPassword);
            result = changePasswordService.updatePasswordById(userId, password);
        }catch (Exception e){
            e.printStackTrace();
        }
        return result;
    }
}
